<?PHP
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | SAPID: XML Sapiens Engine Demonstrator                               |
// +----------------------------------------------------------------------+
// | Author:  Max Baryshnikov aka Mephius <mb@rg.by>	                  |
// | Copyright (c) 2004 Max Baryshnikov                                   |
// | http://sapid.sourceforge.net	                                      |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+
// Release: 06.12.04 (dd/mm/yy)
// $Id: index.php,v 1.13 2006/02/20 08:40:20 mephius Exp $

//Cut off lost picture requests
if (preg_match("/\.[gjpi][ipnc][fgo]/i", $_SERVER['REQUEST_URI'])) exit;


if(!@include (dirname(__FILE__) . "/etc/rc.conf.php")) header("Location: install.php");
if(!@include(ROOT_PATH."etc/rc.d/debug.inc.php")) header("Location: install.php");
if(!$http_path or !is_file(ROOT_PATH . "index.php")) message_die("SAPID not yet been configured or configuration is broken.<br /><br />Please, enter the <a href=\"install.php\">configuration utility</a> and create a new configuration.");
include(ROOT_PATH . "etc/startup.inc.php");

if (!isset($_SESSION["user"]["login"])) {
	include(ROOT_PATH . "usr/system/counter.inc.php");
}else{
	$env["user"]=$_SESSION["user"];
}
include(ROOT_PATH."mvc/controller/user_requests_analysis.inc.php");

if(file_exists(ROOT_PATH."install.php")) this_message_die("Security warning", "<center>You should to delete INSTALL.PHP</center>");


$env["area51"]=0;
if (isset($_SESSION["user"]["LOGIN"]) and $_SESSION["user"]["NOLOGIN"]=="") {
	$env["user.aStatus"]=1;
	$env["area51"]=1;
	if(isset($_GET["mode"])){
		switch ($_GET["mode"]) {
			case "edit":
			if($env["page"]["pWrite"]) {
				$env["mode"]=1;
				$env["area51"]=2;
			}else{
				$env["mode"]=0;
			}
			break;
			default:
			$env["mode"]=0;
			break;
		}
	}
}


if($panel=="") $sapi_obj = new sapi_parser(ROOT_PATH . "usr/templates/" . $env["page"]["TEMPLATE"], $env);



// Looking for an information about current page children
if($tree->map) {
	foreach($tree->map as $k=>$v) {
		if($v["ID"]==$env["page.ID"]) { $curPointer = $v["POINTER"]; break; }
	}
	eval("\$val = \$tree->structure".$curPointer."['CHILDREN'];");
	$env["document.children"] = count($val);
}


$parse=($panel==""?$sapi_obj->build_page():$panel);

$stream="";
if (isset($_SESSION["user"]["LOGIN"]) and $_SESSION["user"]["NOLOGIN"]=="") {

	if($env["mode"]==1){
		// Delete QC in <title>
		$parse = preg_replace("/<title>(.*?)<\/title>/is", "", $parse);
		$parse = preg_replace("/<meta .*?content=\"(.*?)\".*?>/is", "", $parse);
		include("usr/system/metapanel.inc.php");
		$parse = $metapanel.$parse;
	}

	if (isset($_POST["quick_save"])) {
		if ($error_message) $message="<span style='color: #D31412'>".$error_message."</span>";
		else $message="<span style='color: #333399'>Data saved</span>";
		echo '
<html>
<body style="background-color: white; padding: 5px 10px">
<table width="100%" height="100%" border="0">
<tr><td style="font-weight: bold;  text-align: center">'.$message.'</td></tr>
</table>
<script language="javascript1.2"> 
function Hide_Message(){
	top.document.getElementById("message_div").style.left=-300;
	top.document.getElementById("message_div").style.top=-300;	
}

	top.document.getElementById("message_div").style.left=top.document.body.clientWidth/2-100;
	top.document.getElementById("message_div").style.top=top.document.body.clientHeight/2-25+top.document.body.scrollTop;	
	setTimeout(Hide_Message,1500);
</script>
</body>
</html>
';
		exit;
	}

	//$action=$env["http_path"] . ($MODREWRITE=="disabled"?"?vpath=":"").preg_replace("/^\/(.*)\/*$/iU", "\\1/", str_replace("?".$_SERVER["QUERY_STRING"], "", $_SERVER["REQUEST_URI"]));
	$action=$http_path . ($MODREWRITE=="disabled"?"?vpath=":"") . $env["noslash_argv_string"] . ($env["noslash_argv_string"]==""?"":"/");
	if ($env["mode"]==1) {
		include(ROOT_PATH ."usr/system/js/startup.js.php");

		$form_header='
<form action="'.$action.'" method="post" enctype="multipart/form-data" name="bcwb_form" id="bcwb_form" style="padding: 0px; display: none;">
  <input type="hidden" name="update" value="1">

  <input type="hidden" name="arg_ImgUrl" value="">
  <input type="hidden" name="arg_AltText" value="">
  <input type="hidden" name="arg_ImgBorder" value="">
  <input type="hidden" name="arg_HorSpace" value="">
  <input type="hidden" name="arg_VerSpace" value="">
  <input type="hidden" name="arg_ImgAlign" value="">
  <input type="hidden" name="arg_ImgHeight" value="">
  <input type="hidden" name="arg_ImgWidth" value="">
  <input type="hidden" name="arg_FileUrl" value="">	

  '.$GLOBALS["form_fields"]."</form>";
	}

	if(!$panel){
		preg_match("/<title>(.*)<\/title>/isU", $parse, $matches);
		$title=$matches[1];
	}


	// Skin of administrative panel
	include(ROOT_PATH."usr/themes/default/templates/admin_panel.inc.php");

	//mod toxin, browser 
//	$stream=<<<PROLOG
//<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
//"http://www.w3.org/TR/html4/loose.dtd">
//PROLOG;
	
	$admin_block ="
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$default_charset."\" />
<link rel=\"stylesheet\" type=\"text/css\" href=\"".$env["http_path"] . "usr/".($_SESSION["user"]["LOGIN"]?"system":"content")."/".($panel==""?"light.css":"default.css")."\">
<title>".$metatitle."</title>
".($env["mode"]==1?"
<script src=\"".$env["http_path"]."usr/system/js/mozile/mozileLoader.js\" type=\"text/javascript\"></script>
<SCRIPT LANGUAGE=\"JavaScript\">
function ".substr(0, 5, time())."_go(){
".$GLOBALS["action_script"]."
document.getElementById('bcwb_form').submit();
}
</SCRIPT>
":"")."
<script language=\"javascript\">
var id_form_focus=false;
	

function Hide_Message(){
	document.getElementById(\"message_div\").style.left=-300;
	document.getElementById(\"message_div\").style.top=-300;	
}


function do_quick_save(id_form_focus){

	if(document.implementation && document.implementation.createDocument){
	var data='';
	form=document.getElementById(id_form_focus);
	if(form){
		for(i=0; i<form.elements.length; i++){
			if(form.elements.item(i).nodeName=='INPUT' || form.elements.item(i).nodeName=='TEXTAREA') {
				if(form.elements.item(i).name!='' && form.elements.item(i).value!='') data+=(data==''?'':'&')+form.elements.item(i).name+'='+escape(form.elements.item(i).value);
			}
		}
	}
	request=new XMLHttpRequest();
	var method=(form.attributes.getNamedItem('method') && form.attributes.getNamedItem('method').value?form.attributes.getNamedItem('method').value:'GET');
	var action=(form.attributes.getNamedItem('action') && form.attributes.getNamedItem('action').value?form.attributes.getNamedItem('action').value:document.baseURI);
	request.open(method, action, false);
	request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.send(data+'&quick_save=1');
	document.getElementById('message_div').innerHTML='<table width=\"100%\" height=\"100%\" border=\"0\" style=\"background-color: white\"><tr><td style=\"font-weight: bold;  text-align: center; vertical-align: middle; color: #333399; font-size: 12px;\">'+(request.status==200?'Data Saved':'<span style=\"color: red;\">Error</span>')+'</td></tr></table>';

	document.getElementById(\"message_div\").style.left=top.document.body.clientWidth/2-100;
	document.getElementById(\"message_div\").style.top=top.document.body.clientHeight/2-25+top.document.body.scrollTop;	
	setTimeout(Hide_Message,1500);

	
}else{
	if (id_form_focus){

			quick_save.document.write('<HTML><HEAD><META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=".$default_charset."\"></HEAD<BODY><DIV style=\"visibility: hidden\">');
			quick_save.document.write(document.getElementById(id_form_focus).outerHTML.replace(\"</FORM>\",\"<input type='hidden' name='quick_save' value='true' /></FORM>\"));
			quick_save.document.write('</DIV></BODY></HTML>');
			quick_save.document.close();
			quick_save.document.charset=\"".$default_charset."\";
	
			quick_save.document.getElementById(id_form_focus).submit();
		}
	}
}
	
	
function getKeyDown(ev) {
	if(document.implementation && document.implementation.createDocument){
	var data='';
	form=document.getElementById(id_form_focus);
		if(form && ev.charCode==115 && ev.ctrlKey) {
			ev.preventDefault();
			do_quick_save(id_form_focus);
			return false;
		}
	}else{
			if (window.event.keyCode==83 && window.event.ctrlKey && id_form_focus) {
				do_quick_save(id_form_focus);
				return false;	
			}
		}
}

if(window.addEventListener) {
	window.addEventListener('keypress', getKeyDown, true);	
} else document.onkeydown = getKeyDown;
".($env["mode"]==1?$add_js:"")."	
</script>
".($_GET["mode"]=="edit" ? "<script type=\"text/javascript\" src=\"".$env["http_path"]."usr/system/html2xhtml.js\"></script>" : "")."	
</head>
<body "./*($panel==""?"onscroll=\"move_panel();\"":"").*/">
<div id=\"message_div\" style=\"position:absolute; top:-300px; left:-300px; width:300px; border: solid 1px #9EB9CC; height:75px; vertical-align: middle;\"><iframe name=\"quick_save\"  scrolling=\"no\" id=\"quick_save\" style=\"width:300; height:75;\" frameborder=0></iframe></div>
<table width=\"100%\" height=\"100%\" cellpadding=0 cellspacing=0 border=0><tr><td height=\"100%\" colspan=2 style=\"vertical-align: top;\">
".$tools.($env["mode"]==1?$form_header:"");
	
	if(!isset($_GET["option"]) AND preg_match("/(<body[^>]*?>)/is", $parse))
		$stream .= preg_replace("/(<body[^>]*?>)/is", "\\1".$admin_block, $parse);
	else
		$stream .= $admin_block . $parse;
	
$stream .= "
</td></tr>
<tr><td style=\"vertical-align : middle; width: 400px; height: 15px; background-color: #003263; color: white; \"><a class=\"sapidcms_white\" href=\"http://sapid.sourceforge.net\">Sapid v".$VERSION."</a>&nbsp;<span style=\"color: white; font-size: 10px; vertical-align : middle;\">Configured:&nbsp;".$CONFIGURED."</span></td><td nowrap=\"nowrap\" style=\"height: 15px; background-color: #003263; vertical-align : middle;\">
<a class=\"sapidcms_white\" href=\"http://www.sapid-club.com/wiki/\" title=\"Find your questions out at SAPID Live Encyclopedia\">SAPID Wiki</a>
<a class=\"sapidcms_white\" href=\"http://www.sapidfarm.com\" title=\"You can place your project here\">SAPID Farm</a> <a class=\"sapidcms_white\" href=\"http://www.sapid-club.com\" title=\"You can place your question here\">SAPID-CLUB</a> <a class=\"sapidcms_white\" href=\"http://www.redgraphic.com\">Red Graphic Systems Sponsored</a></td></tr></table>
</body>
</html>
";



}else $stream=$parse;


if (preg_match("/DOCTYPE\swml/isU", trim(substr($stream,0,250)))) {
	header("Content-Type: text/vnd.wap.wml; charset=UTF-8");
} elseif (preg_match("/^<\?xml/isU", trim(substr($stream,0,50)))) {
	header("Content-type: text/xml; charset=UTF-8");
} else {
	header("Content-type: text/html; charset=UTF-8");
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
}


if ($MODREWRITE=="disabled") {
	$stream=preg_replace("/".preg_quote($http_path, "/")."usr\/templates\/files/isU", "|{$http_path}usr/templates/files", $stream);
	
	$stream=preg_replace("/(<a[\sa-zA-Z\"\._\-=\;\:]+)href=(\"|')?(?:".addcslashes($http_path, "/")."|\/)([^\?]){1}([^\s\"\'\?]{0,})(\"|')?([\sa-zA-Z\"\._\-=]*)>/isU", "\\1href=\\2?vpath=/\\3\\4\\5\\6>", $stream);
	$stream=preg_replace("/location=(\"|')?(?:".addcslashes($http_path, "/")."|\/)([^\?]{1})([^\s\"\'\?]{0,})(\"|')?/is", "location=\\1".$http_path."?vpath=/\\2\\3\\4", $stream);
	$stream=preg_replace("/(<form[\sa-zA-Z\"\._\-=\;\:]+)action=(\"|')(?:".addcslashes($http_path, "/")."|\/)([^\?]){1}([^\s\"\'\?]{0,})(\"|')([\sa-zA-Z\"\._\-=]*)>/isU", "\\1action=\\2?vpath=/\\3\\4\\5\\6>", $stream);
	
	$stream=preg_replace("/(href=\"\|)/isU", "href=\"", $stream);
} elseif ($MODREWRITE=="MultiviewsMode") {
	// Link to site chapter (not to file)
	$stream=preg_replace("/href=\"".preg_quote($env["http_path"],"/")."([^\.]+)\"/isU", "href=\"{$http_path}\\1\"", $stream);
	// Link to real file
	$stream=preg_replace("/href=\"".preg_quote($http_path,"/")."([\.]+)\"/isU", "href=\"{$env["http_path"]}\\1\"", $stream);
}

$env["time_finish"]=getmicrotime();
$env["exec_time"]=$env["time_finish"]-$env["time_start"] . " sec";

$stream=str_replace("##gentime##", $env["exec_time"], $stream);
echo $stream;

if($error_stack)  echo "<div style=\"position: absolute; top: 40%; left: 40%; background-color: #D9D9D9; border: 1px solid red; padding: 10px; width: 280px; position: absolute; height: 40px; display: block; \"/>".$error_stack."</div>";
elseif ($sapi_obj->error and $_SESSION["user"]["LOGIN"]) echo "<div style=\"position: absolute; top: 40%; left: 40%; background-color: #D9D9D9; border: 1px solid red; padding: 10px; width: 280px; position: absolute; height: 40px; display: block; \"/><b style=\"color: red;\">Error!</b><br /><span style=\"font-size: 10px;\">".$sapi_obj->error."</span></div>";
if($_GET["d"]=="perf" and DEBUG) echo "<div style=\"background-color: Silver; border: 1px solid maroon; padding: 10px; width: 310px; position: absolute; top: 45%; left:36%; height: 40px; display: block; \"/>Execution time: " . $env["exec_time"] . "</div>";
unset($sapi_obj);
?>  